package com.gongpingjialoan.activity.sell;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.category.CategoryActivity;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.activity.main.SelectAddressActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.activity.tool.WebViewActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.SellPrivateCarBean;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.UserLocation;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.DatePickerDialog;
import com.gongpingjialoan.view.SellSameCarDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2016/8/2.
 */
public class SellPrivateActivity extends BaseActivity implements View.OnClickListener {

    private static final int GETADDRESS = 10;

    private final int REQUEST_CITY_FRAGMENT = 1;

    private static final int REQUEST_BRAND = 2;

    private TextView carTypeText, dateLicenseText, cityText, addressTextView;

    private EditText mDistanceEdit, priceEditText;

    private AssessmentData mAssessData;

    private NetDataJson mNetModelDetail;

    private SellPrivateCarBean mSellPrivateCarBean;

    private EditText userEditText, phoneEditText;

    private UserManager mUserManager;

    private NetDataJson sameNetDataJson;

    /**
     * 日期选择弹框
     */
    private String mMile;

    private DatePickerDialog dateDialog;

    private String mYear, mMonth, maxyear, minyear, mBrandSlug, mBrandName, mModelSlug, mModelName, mModelDetailName,
            mModelDetailSlug;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "sell_pubCarSource_main";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_car);
        mUserManager = new UserManager(this);
        mUserManager = mUserManager.LoadUserInfo();
        setTitle("个人卖车");
        initView();
    }

    private void initView() {
        addressTextView = (TextView) findViewById(R.id.seecar_address);
        carTypeText = (TextView) findViewById(R.id.tv_car_type);
        dateLicenseText = (TextView) findViewById(R.id.tv_date_license);
        cityText = (TextView) findViewById(R.id.tv_city);
        mDistanceEdit = (EditText) findViewById(R.id.et_distance_run);
        priceEditText = (EditText) findViewById(R.id.price);
        phoneEditText = (EditText) findViewById(R.id.phone);
        userEditText = (EditText) findViewById(R.id.user);
        carTypeText.setOnClickListener(this);
        dateLicenseText.setOnClickListener(this);
        addressTextView.setOnClickListener(this);
        cityText.setOnClickListener(this);

        initData();
        initLinister();
        initNoknow();
    }


    private void initLinister() {
        mDistanceEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mSellPrivateCarBean.mile = mDistanceEdit.getText().toString();
            }
        });

        phoneEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mSellPrivateCarBean.phone = phoneEditText.getText().toString();
            }
        });

        userEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mSellPrivateCarBean.contract = userEditText.getText().toString();
            }
        });

        priceEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mSellPrivateCarBean.maxPrice = priceEditText.getText().toString();
            }
        });

    }

    private void initNoknow() {
        View view = findViewById(R.id.no_know);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SellPrivateActivity.this, WebViewActivity.class);
                intent.putExtra("url", Const.maiche);
                intent.putExtra("content", "过户6大证件");
                startActivity(intent);
            }
        });

    }


    private void initData() {
        mSellPrivateCarBean = SellPrivateCarBean.getInstance();
        mAssessData = AssessmentData.getInstance();
        mBrandSlug = mAssessData.getBrandSlug();
        if (TextUtils.isEmpty(mBrandSlug))
            return;
        mBrandName = mAssessData.getBrandName();
        mModelSlug = mAssessData.getModelSlug();
        mModelName = mAssessData.getModelName();
        mModelDetailName = mAssessData.getModelDetailName();
        mModelDetailSlug = mAssessData.getModelDetailSlug();
        carTypeText.setText(mAssessData.getModelName() + " " + mAssessData.getModelDetailName());
        dateLicenseText.setText(mAssessData.getYear() + "年" + mAssessData.getMonth() + "月");
        mYear = mAssessData.getYear();
        mMonth = mAssessData.getMonth();
        double m = Double.parseDouble(mAssessData.getMile());
        if (m % 1 == 0) {
            mDistanceEdit.setText((int) m + "");
        } else {
            mDistanceEdit.setText(mAssessData.getMile());
        }
        cityText.setText(mAssessData.getCity());

        mSellPrivateCarBean.brandName = mBrandName;
        mSellPrivateCarBean.brandSlug = mBrandSlug;
        mSellPrivateCarBean.modelName = mModelName;
        mSellPrivateCarBean.modelSlug = mModelSlug;
        mSellPrivateCarBean.modelDetailName = mModelDetailName;
        mSellPrivateCarBean.modelDetailSlug = mModelDetailSlug;
        mSellPrivateCarBean.mile = mAssessData.getMile();
        mSellPrivateCarBean.city = mAssessData.getCity();
        mSellPrivateCarBean.year = mAssessData.getYear();
        mSellPrivateCarBean.month = mAssessData.getMonth();
        priceEditText.setText(mSellPrivateCarBean.maxPrice);
        userEditText.setText(mSellPrivateCarBean.contract);
        if(TextUtils.isEmpty(mSellPrivateCarBean.address)){
            addressTextView.setText(UserLocation.getInstance().getAddress());
            mSellPrivateCarBean.address = UserLocation.getInstance().getAddress();
            mSellPrivateCarBean.address_title = UserLocation.getInstance().getAddresstitle();
        }else{
            addressTextView.setText(mSellPrivateCarBean.address);
        }
        if (TextUtils.isEmpty(mSellPrivateCarBean.phone)) {
            if (!TextUtils.isEmpty(mUserManager.getPhone())) {
                phoneEditText.setText(mUserManager.getPhone());
            }
        } else {
            phoneEditText.setText(mSellPrivateCarBean.phone);
        }

        getMaxMinYear();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            // Bundle bundle = data.getExtras();
            switch (requestCode) {
                case REQUEST_BRAND:
                    Bundle bundle = data.getExtras();
                    onBrandSelceted(bundle);
                    break;
                // 城市选择回调
                case REQUEST_CITY_FRAGMENT:
                    Bundle b = data.getExtras();
                    String city = b.getString("city");
                    if (!TextUtils.isEmpty(city)) {
                        cityText.setText(city);
                        mSellPrivateCarBean.city = city;
                    }
                    break;
                case GETADDRESS:
                    String title = data.getExtras().getString("address_title");
                    String address = title + data.getExtras().getString("address_detail");
                    //  Toast.makeText(this, data.getExtras().getString("address_title"), Toast.LENGTH_SHORT).show();
                    addressTextView.setText(address);
                    mSellPrivateCarBean.address = address;
                    mSellPrivateCarBean.address_title = title;
                    break;
            }
        }
    }


    // 选择完车型后,调用这辆
    public void onBrandSelceted(Bundle bundle) {
        mBrandSlug = bundle.getString("brandSlug");
        mBrandName = bundle.getString("brandName");
        mModelSlug = bundle.getString("modelSlug");
        mModelName = bundle.getString("modelName");
        mModelDetailName = bundle.getString("modelDetailName");
        mModelDetailSlug = bundle.getString("modelDetailSlug");

        mSellPrivateCarBean.brandName = mBrandName;
        mSellPrivateCarBean.brandSlug = mBrandSlug;
        mSellPrivateCarBean.modelName = mModelName;
        mSellPrivateCarBean.modelSlug = mModelSlug;
        mSellPrivateCarBean.modelDetailName = mModelDetailName;
        mSellPrivateCarBean.modelDetailSlug = mModelDetailSlug;

        // 查询二手车,选择车型后,车辆型号TextView的展示
        if (mModelDetailName == null) {
            carTypeText.setText(mModelName);
        } else {
            carTypeText.setText(mModelName + " " + mModelDetailName);
        }
        maxyear = bundle.getString("maxyear");
        minyear = bundle.getString("minyear");

        // 上牌年份选择弹框
        dateDialog = new DatePickerDialog(SellPrivateActivity.this);
        dateDialog.setMinMonth(1);
        dateDialog.setMaxMonth(12);
        dateDialog.setDialogCallBack(new DatePickerDialog.OnDialogCallBack() {

            @Override
            public void onSelectResult(String year, String month, String day) {
                mYear = year;
                mMonth = month;
                if (TextUtils.isEmpty(month)) {
                    dateLicenseText.setText(year + "年");
                } else {
                    dateLicenseText.setText(year + "年" + month + "月");
                }
                mSellPrivateCarBean.year = mYear;
                mSellPrivateCarBean.month = mMonth;
            }
        });

        dateDialog.setMonthPickerVisibility(View.VISIBLE);
        dateDialog.setMinYear(Integer.parseInt(minyear));
        dateDialog.setMaxYear(Integer.parseInt(maxyear));
        if (maxyear == null) {
            Toast.makeText(this, "没有可选的上牌时间!", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        mDistanceEdit.setText(null);

        if (TextUtils.isEmpty(carTypeText.getText().toString())
                || carTypeText.getText().toString().equals("请选择")) {
            Toast.makeText(this, "请选择车辆型号!",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (null != dateDialog && maxyear != null) {
            dateDialog.show();
        } else {
            Toast.makeText(this, "上牌时间数据加载中!",
                    Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        Intent intent;
        switch (id) {

            case R.id.tv_car_type:
                intent = new Intent();
                intent.setClass(this, CategoryActivity.class);
                intent.putExtra(Const.BRAND_NAME_KEY, mBrandName);
                intent.putExtra(Const.BRAND_SLUG_KEY, mBrandSlug);
                intent.putExtra(Const.MODEL_NAME_KEY, mModelName);
                intent.putExtra(Const.MODEL_SLUG_KEY, mModelSlug);
                intent.putExtra(Const.MODEL_DETAIL_NAME_KEY, mModelDetailName);
                intent.putExtra(Const.MODEL_DETAIL_SLUG_KEY, mModelDetailSlug);
                intent.putExtra("needModelDetailFragment", true);
                startActivityForResult(intent, REQUEST_BRAND);
                break;
            case R.id.tv_city:
                intent = new Intent();
                intent.putExtra("needProvince", false);
                intent.setClass(this, CityActivity.class);
                startActivityForResult(intent, REQUEST_CITY_FRAGMENT);
                break;
            case R.id.tv_date_license:
                if (TextUtils.isEmpty(carTypeText.getText().toString())
                        || carTypeText.getText().toString().equals("请选择")) {
                    Toast.makeText(this, "请选择车辆型号!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (null != dateDialog && maxyear != null) {
                    dateDialog.show();
                } else {
                    Toast.makeText(this, "上牌时间数据加载中!",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.seecar_address:
                Intent addressIntent = new Intent(this, SelectAddressActivity.class);
                startActivityForResult(addressIntent, GETADDRESS);
                break;


        }
    }

    private void getMaxMinYear() {

        if (mNetModelDetail == null) {
            mNetModelDetail = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {

                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    if (null == json) {
                        return;
                    }

                    try {
                        JSONArray detail = json.getJSONArray("detail_model");
                        if (null == detail) {
                            return;
                        }
                        for (int i = 0; i < detail.length(); i++) {
                            JSONObject jo = detail.getJSONObject(i);
                            if (null != jo) {
                                if (mModelDetailSlug.equals(jo.getString("detail_model_slug"))) {
                                    minyear = jo.getString("min_reg_year");
                                    maxyear = jo.getString("max_reg_year");
                                    break;
                                }
                            }
                        }
                    } catch (JSONException e) {
                    }
                    // 上牌年份选择弹框
                    dateDialog = new DatePickerDialog(SellPrivateActivity.this);
                    dateDialog.setMinMonth(1);
                    dateDialog.setMaxMonth(12);
                    dateDialog.setDialogCallBack(new DatePickerDialog.OnDialogCallBack() {

                        @Override
                        public void onSelectResult(String year, String month, String day) {
                            mYear = year;
                            mMonth = month;
                            if (TextUtils.isEmpty(month)) {
                                dateLicenseText.setText(year + "年");
                            } else {
                                dateLicenseText.setText(year + "年" + month + "月");
                            }
                        }
                    });
                    dateDialog.setMonthPickerVisibility(View.VISIBLE);
                    dateDialog.setMinYear(Integer.parseInt(minyear));
                    dateDialog.setMaxYear(Integer.parseInt(maxyear));
                }
            });
        }
        mNetModelDetail.setUrl(API.modelDetail);
        mNetModelDetail.addParam("brand", mBrandSlug);
        mNetModelDetail.addParam("model", mModelSlug);
        mNetModelDetail.request("get");

    }


    public void step1(View v) {
        if (TextUtils.isEmpty(mBrandSlug)) {
            Toast.makeText(this, "请选择车辆型号!",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(dateLicenseText.getText().toString())) {
            Toast.makeText(this, "请选择上牌时间!",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        mMile = mDistanceEdit.getText().toString();

        Double mile = -1.0;

        if (TextUtils.isEmpty(mMile)) {
            Toast.makeText(this, "请输入行驶里程!",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (mMile.length() > 5) {
            Toast.makeText(this,
                    "请输入正确的公里数，小数和整数均不能超过2位数!", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        try {
            mile = Double.valueOf(mMile);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请填写正确的行驶里程（0-100万公里）",
                    Toast.LENGTH_SHORT).show();
            return;

        }
        if (mile < 0 || mile > 100) {
            Toast.makeText(this, "请填写正确的行驶里程（0-100万公里）",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        mMile = mile + "";

        String address = addressTextView.getText().toString();
        if (TextUtils.isEmpty(address)) {
            Toast.makeText(this, "请输入看车地点",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        String maxPrice = priceEditText.getText().toString();
        if (TextUtils.isEmpty(maxPrice)) {
            Toast.makeText(this, "请输入预期价格",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        String users = userEditText.getText().toString();
        if (TextUtils.isEmpty(users)) {
            Toast.makeText(this, "请输入联系人",
                    Toast.LENGTH_SHORT).show();
            return;
        }


        String phone = phoneEditText.getText().toString();
        if (TextUtils.isEmpty(phone) || phone.length() < 11) {
            Toast.makeText(this, "请输入正确的电话号码",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        mSellPrivateCarBean.mile = mMile;
        mSellPrivateCarBean.maxPrice = maxPrice;
        mSellPrivateCarBean.contract = users;
        mSellPrivateCarBean.phone = phone;
        getIfSameCar();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sameNetDataJson != null) {
            sameNetDataJson.cancelTask();
            sameNetDataJson = null;
        }
    }



    //是否重复购买
    private void getIfSameCar() {
        showProgressDialog("加载中...");
        if (sameNetDataJson == null) {
            sameNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    hidenProgressDialog();
                    startActivity(new Intent(SellPrivateActivity.this, SellPrivateStepActivity2.class));
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    hidenProgressDialog();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = json.getJSONObject("data");
                        if (jsonObject != null && jsonObject.length() > 0) {
                            String title = jsonObject.getString("model_detail_zh");
                            String time = Utils.getParseDay("yyyy-MM-dd HH:mm:ss", jsonObject.getString("create_time"));
                            String msg = "您已在" + time + " ,提交一辆" + title + " 您已无需重复提交";
                            SellSameCarDialog sellSameCarDialog = new SellSameCarDialog(SellPrivateActivity.this, msg, new SellSameCarDialog.ISellSameCar() {
                                @Override
                                public void sellSmaeCar() {
                                    startActivity(new Intent(SellPrivateActivity.this, SellPrivateStepActivity2.class));
                                }

                                @Override
                                public void refresh() {
                                    Intent intent = new Intent(SellPrivateActivity.this, MainActivity.class);
                                    intent.putExtra("type" , "sell_private_car");
                                    startActivity(intent);
                                }
                            } , true);
                            sellSameCarDialog.show();
                        } else {
                            startActivity(new Intent(SellPrivateActivity.this, SellPrivateStepActivity2.class));
                        }
                    } catch (Exception e) {
                    }

                }
            });
        }
        sameNetDataJson.setUrl("/mobile/sell/car/get-check-duplicated-selling/");
        sameNetDataJson.addParam("brand", mBrandSlug);
        sameNetDataJson.addParam("model", mModelSlug);
        sameNetDataJson.addParam("model_detail", mModelDetailSlug);
        sameNetDataJson.addParam("type", "personal");
        sameNetDataJson.request("get");
    }


}
